package com.atguigu.ggkt.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringTool {

    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static void setApplicationContext(ApplicationContext context) {
        SpringTool.context = context;
    }

    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static Object getProperty(String propertyName){
        Environment env = (Environment)context.getBean("environment");
        return env.getProperty(propertyName);
    }

    public static <T> T getSpringBeanNoThrow(String beanName){
        T bean = null;
//        ApplicationContext ctx = WebApplicationContextUtils
//                .getWebApplicationContext(servletContext);

        try {
            if (context.getBean(StringUtils.uncapitalize(beanName)) != null) {
                bean = (T)context.getBean(StringUtils.uncapitalize(beanName));
            }
        } catch (Exception e) {
            LogTool.debug(SpringTool.class, "getSpringBeanNoThrow, can not get bean:"+beanName);
        }

        return bean;
    }


    public static <T> T getSpringBean(String beanName){
        T bean = null;
//        ApplicationContext ctx = WebApplicationContextUtils
//                .getWebApplicationContext(servletContext);

        if (context.getBean(StringUtils.uncapitalize(beanName)) != null) {
            bean = (T)context.getBean(StringUtils.uncapitalize(beanName));
        }

        return bean;
    }

    public static <T> T getSpringBeanThrows(String beanName) throws Exception {

        if (getSpringBean(beanName) == null) {
            throw new Exception("can not get bean:"+beanName);
        }
        T bean = (T)getSpringBean(beanName) ;
        return bean;
    }

    public static <T> T getSpringBean(Class<T> t) {
        String beanName = StringUtils.uncapitalize(t.getSimpleName());

        if (context.getBean(beanName) == null) {
            return null;
        }
        T bean = (T)context.getBean(beanName) ;
        return bean;
    }

    public static void printBeanInfo() {

        String[] beanNames = context.getBeanDefinitionNames();

        for (String beanName : beanNames) {

            System.out.println(beanName);

        }

    }

}
